#include "FrameWorker.h"
#include "Logger.h"
#include "System.h"
#include "OS.h"

FrameWorker::FrameWorker()
: time_slice_ms_(40)
, time_max_frame_ms_(40)
, time_tick_slice_ms_(1000)
, last_update_time_(0)
, total_poll_times_(0)
, expired_poll_times_(0)
, time_tick_surplus_ms_(0)
{
}

FrameWorker::~FrameWorker()
{
}

bool FrameWorker::Initialize()
{
    last_update_time_ = GET_REAL_SYS_TIME;
    return Thread::Initialize();
}

void FrameWorker::Kernel()
{
    uint64 start_update_time = GET_REAL_SYS_TIME;
    uint64 diffTime = start_update_time - last_update_time_;
    last_update_time_ = start_update_time;

    Update(diffTime);
    ++total_poll_times_;

    if ((time_tick_surplus_ms_ += diffTime) >= time_tick_slice_ms_) {
        time_tick_surplus_ms_ = 0;
        OnTick();
    }

    uint64 end_update_time = GET_REAL_SYS_TIME;
    uint64 expend_ms = end_update_time - start_update_time;
    if (expend_ms < time_slice_ms_) {
        Idle(time_slice_ms_ - expend_ms);
    } else if (expend_ms > time_max_frame_ms_) {
        if (++expired_poll_times_ % 30 == 0) {
            WLOG("%s::Kernel(): expend_ms[%llu] exceed TIME_SLICE_MS[%llu].",
                GetThreadName(), expend_ms, time_slice_ms_);
        }
    }
}

void FrameWorker::Idle(uint64 ms)
{
    OS::SleepMS((long)ms);
}
